package net.chasing.retrofit.util.encode;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 加密解密类
 */
public class CodeUtils {

    /**
     * Base64加密字符串
     *
     * @param content -- 代加密字符串
     */
    public static String base64Encode(String content) {
        return base64Encode(content, "UTF-8", Base64.NO_WRAP);
    }

    /**
     * Base64加密字符串
     *
     * @param content     -- 代加密字符串
     * @param charsetName -- 字符串编码方式
     */
    public static String base64Encode(String content, String charsetName, int flags) {
        if (TextUtils.isEmpty(charsetName)) {
            charsetName = "UTF-8";
        }
        try {
            byte[] contentByte = content.getBytes(charsetName);
            return Base64.encodeToString(contentByte, flags);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    //SHA1 加密实例
    public static String sha1(String info) {
        byte[] digesta = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将摘要转为字符串
        return byte2hex(digesta);
    }

    /**
     * 对字符串数组进行排序，按ASCII码从小到大
     */
    public static String[] orderByASCII(String[] keys) {
        for (int i = 0; i < keys.length - 1; i++) {
            for (int j = 0; j < keys.length - i - 1; j++) {
                String pre = keys[j];
                String next = keys[j + 1];
                if (isMoreThan(pre, next)) {
                    keys[j] = next;
                    keys[j + 1] = pre;
                }
            }
        }
        return keys;
    }

    public static String changeFromUnicode(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        Pattern pattern = Pattern.compile("\\\\u[0-9a-fA-F]{4}");
        Matcher matcher = pattern.matcher(str);
        int startIndex = 0;
        while (matcher.find()) {
            try {
                String group = matcher.group();
                int start = matcher.start();
                int end = matcher.end();
                // 将Unicode码值转成16进制的ascii码值，转成char得到正确的字符
                int num = Integer.parseInt(group.substring(2), 16);
                char c = (char) num;
                if (start > startIndex) {
                    stringBuilder.append(str.substring(startIndex, start));
                }
                stringBuilder.append(c);
                startIndex = end;
            } catch (Exception e) {
                if (!TextUtils.isEmpty(e.getMessage()))
                    Log.e("", e.getMessage());
            }
        }
        if (startIndex < str.length()) {
            stringBuilder.append(str.substring(startIndex));
        }
        str = stringBuilder.toString();
        return str;
    }

    private static boolean isMoreThan(String pre, String next) {
        if (null == pre || null == next || "".equals(pre) || "".equals(next)) {
            return false;
        }
        char[] c_pre = pre.toCharArray();
        char[] c_next = next.toCharArray();
        int minSize = Math.min(c_pre.length, c_next.length);

        for (int i = 0; i < minSize; i++) {
            if ((int) c_pre[i] > (int) c_next[i]) {
                return true;
            } else if ((int) c_pre[i] < (int) c_next[i]) {
                return false;
            }
        }
        return c_pre.length > c_next.length;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str 待转换的ASCII字符串
     * @return 如: [616C6B]
     */
    public static String str2HexStr(String str, String charsetName) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder();
        byte[] bs;
        try {
            bs = str.getBytes(charsetName);
        } catch (UnsupportedEncodingException e) {
            bs = str.getBytes();
        }
        int bit;

        for (byte b : bs) {
            bit = (b & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = b & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 十六进制转换字符串
     *
     * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr, String charsetName) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        try {
            return new String(bytes, charsetName);
        } catch (UnsupportedEncodingException e) {
            return new String(bytes);
        }
    }

    public static byte[] hexStr2HexByte(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return bytes;
    }

    public static byte[] intToHexByte(int val) {
        String s = Integer.toHexString(val);
        if (s.length() % 2 != 0) {
            s = "0" + s;
        }
        return string2Byte(s);
    }

    public static int hexByte2Int(byte[] bytes) {
        String numStr = byte2String(bytes);
        return Integer.parseInt(numStr, 16);
    }

    public static byte[] string2Byte(String s) {
        s = s.replace(" ", "");
        s = s.replace("#", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return baKeyword;
    }

    public static String byte2String(byte[] data) {
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[data.length * 2];

        for (int j = 0; j < data.length; j++) {
            int v = data[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }

        String result = new String(hexChars);
        result = result.replace(" ", "");
        return result;
    }

    public static String byte2hex(byte[] b) {
        if (b == null) return "";
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (byte value : b) {
            stmp = (Integer.toHexString(value & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }
        return hs.toString().toUpperCase();
    }

    public static long getUidFromBase64(String base64Id) {
        long uid = -1L;
        if (!TextUtils.isEmpty(base64Id)) {
            String result;
            if (!TextUtils.isEmpty(base64Id)) {
                result = new String(Base64.decode(base64Id.getBytes(), Base64.DEFAULT));
                uid = Long.parseLong(result);
            }
        }
        return uid;
    }

    /**
     * 获取一条随机字符串
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String toAsciiStr(String str) {
        if (!TextUtils.isEmpty(str)) {
            StringBuilder sb = new StringBuilder();
            for (char c : str.toCharArray()) {
                sb.append((int) c).append(",");
            }
            return sb.toString();
        } else
            return "";
    }
}
